/**
 * @description 级联下拉框 常用于省市区选择
 */
import React from "react";
import { Cascader } from "antd";
const options = [
    {
        value: 'zhejiang',
        label: 'Zhejiang',
        children: [
            {
                value: 'hangzhou',
                label: 'Hangzhou',
                children: [
                    {
                        value: 'xihu',
                        label: 'West Lake',
                    },
                ],
            },
        ],
    },
    {
        value: 'jiangsu',
        label: 'Jiangsu',
        children: [
            {
                value: 'nanjing',
                label: 'Nanjing',
                children: [
                    {
                        value: 'zhonghuamen',
                        label: 'Zhong Hua Men',
                    },
                ],
            },
        ],
    },
];

let areadt = sessionStorage.getItem("areaDt") ? JSON.parse(sessionStorage.getItem("areaDt")) : options
const XxCascader = (props) => {
    const { defaultValue, options = areadt, onSelect = () => { } } = props;
    const onChange = (value) => {
        console.log(value)
        getLabelInValue(value)
    }

    // 传入["id","id","id"] 获得它的label
    const getLabelInValue = (array) => {

        let resList = [];
        array.forEach((item, index) => {
            resList.push({
                label: getLabel(item, index),
                value: item
            })
        })
        onSelect(resList)
    }

    // 传入id 获取 label
    const getLabel = (id, index) => {
        let labelName = "";
        // 递归找
        const fun = (list, id) => {
            list.forEach(item => {
                if (item.code === id) {
                    labelName = item.name;
                    return;
                }
                else if (item.children && item.children.length > 0) {
                    fun(item.children, id)
                }
            })

        }
        fun(areadt, id)

        return labelName;

    }
    return (
        <>
            <Cascader
                options={options}
                defaultValue={defaultValue}
                onChange={onChange}
                fieldNames={{
                    label: "name",
                    value: 'code'
                }}
            />
        </>
    )
}

export default XxCascader;